//
//  HomeAddViewController.swift
//  fruit-helper-swift
//
//  Created by 赵隆杰 on 2022/6/13.
//

import UIKit
import Toast



class HomeAddViewController: BaseViewController, UITextFieldDelegate {
    
    private var bgView: UIView!
    private var imageView: UIImageView!
    private var nameField: UITextField!
    private var contentField: UITextField!
    
    private var bookTitle: NSString = ""//书名
    private var authorTitle: NSString = ""//作者
    private var bookImage: UIImage?
    
    var backEnve : backEnveClosureType?
    

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .clear

        
        setupUI()
        
        
    }
    
    
    
    
    
}



//设置UI
extension HomeAddViewController {
    
    private func setupUI() {
        bgView = UIView()
        bgView.backgroundColor = .white
        view.addSubview(bgView)
        bgView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalToSuperview().offset(200)
        }
        
        let closeBtn = UIButton()
        closeBtn.setImage(UIImage(named: "close"), for: .normal)
        closeBtn.addTarget(self, action: #selector(dismissBtnClick), for: .touchUpInside)
        bgView.addSubview(closeBtn)
        closeBtn.snp.makeConstraints { make in
            make.width.height.equalTo(50)
            make.right.equalToSuperview().offset(-10)
            make.top.equalToSuperview().offset(10)
        }
        
        let centerTitleLabel = UILabel()
        centerTitleLabel.text = "添加书单"
        centerTitleLabel.font = UIFont.boldSystemFont(ofSize: 20)
        bgView.addSubview(centerTitleLabel)
        centerTitleLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(closeBtn)
        }
        
        nameField = UITextField()
        nameField.placeholder = "请填写书名"
        nameField.borderStyle = .roundedRect
        nameField.delegate = self
        nameField.addTarget(self, action: #selector(changedTextField(_:)), for: .editingChanged)
        bgView.addSubview(nameField)
        nameField.snp.makeConstraints { make in
            make.top.equalTo(centerTitleLabel.snp.bottom).offset(20)
            make.right.equalToSuperview().offset(-20)
            make.left.equalTo(80)
            make.height.equalTo(40)
        }
        
        let titleLabel = UILabel()
        titleLabel.text = "书名"
        bgView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.centerY.equalTo(nameField)
        }
        
        contentField = UITextField()
        contentField.placeholder = "请填写作者"
        contentField.borderStyle = .roundedRect
        contentField.delegate = self
        contentField.addTarget(self, action: #selector(changedTextField(_:)), for: .editingChanged)
        bgView.addSubview(contentField)
        contentField.snp.makeConstraints { make in
            make.top.equalTo(nameField.snp.bottom).offset(10)
            make.left.height.right.equalTo(nameField)
        }
        
        let contentLabel = UILabel()
        contentLabel.text = "作者"
        bgView.addSubview(contentLabel)
        contentLabel.snp.makeConstraints { make in
            make.left.equalTo(titleLabel)
            make.centerY.equalTo(contentField)
        }
        
        imageView = UIImageView()
        imageView.layer.cornerRadius = 5
        imageView.layer.masksToBounds = true
        imageView.contentMode = .scaleAspectFit
        imageView.isUserInteractionEnabled = true
        imageView.image = UIImage(named: "picture_add")
        let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(addImage))
        imageView.addGestureRecognizer(tapGesture)
        bgView.addSubview(imageView)
        imageView.snp.makeConstraints { make in
            make.top.equalTo(contentField.snp.bottom).offset(10)
            make.height.equalTo(150)
            make.width.equalTo(imageView.snp.height).multipliedBy(640.0/749.0)
            make.left.equalTo(contentField)
        }
        
        let iconLabel = UILabel()
        iconLabel.text = "封面"
        bgView.addSubview(iconLabel)
        iconLabel.snp.makeConstraints { make in
            make.left.equalTo(contentLabel)
            make.centerY.equalTo(imageView)
        }
        
        
        
        
        
        
        let addButton = UIButton()
        addButton.setTitle("添加书单", for: .normal)
        addButton.setTitleColor(.white, for: .normal)
        addButton.backgroundColor = kThemeColor
        addButton.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        addButton.layer.cornerRadius = 25
        addButton.layer.masksToBounds = true
        addButton.addTarget(self, action: #selector(confirmBtnClick), for: .touchUpInside)
        bgView.addSubview(addButton)
        addButton.snp.makeConstraints { make in
            make.left.equalTo(50)
            make.height.equalTo(50)
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-20-view.safeAreaInsets.bottom)
        }
    }
    
    //bgView以外区域
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        if let touch = touches.first {
            let location = touch.location(in: view)
            let convertPoint = view.convert(location, to: bgView)
            if !bgView.bounds.contains(convertPoint) {
                dismissBtnClick()
            }
        }
    }
}

extension HomeAddViewController {
    @objc private func changedTextField(_ textField: UITextField) {
        if textField == nameField {
            self.bookTitle = (textField.text ?? "") as NSString
        }
        if textField == contentField {
            self.authorTitle = (textField.text ?? "") as NSString
        }
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.endEditing(true)
        return true
    }
    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        textField.endEditing(true)
        return true
    }
    
    @objc private func dismissBtnClick() {
        
        dismiss(animated: true) {
            
        }
    }
    @objc private func addImage() {
        view.endEditing(true)
        ImageUpload.shared.addImageUploadBlock { image in
            self.bookImage = image
            self.imageView.image = image
        }
    }
    
    @objc private func confirmBtnClick() {
        view.endEditing(true)
        
        if self.bookTitle.length == 0 {
            UIWindow().currentWindow()?.makeToast("请填写书名", duration: 1.0, position: CSToastPositionCenter)
            return
        }
        if self.bookImage == nil {
            UIWindow().currentWindow()?.makeToast("请上传图书封面", duration: 1.0, position: CSToastPositionCenter)
            return
        }
        
        let key = String(LocalData().allHomeBooksCount())
        let imageStr = String.getStrFromImage(self.bookImage!)
        
        let model: BookModel = BookModel()
        model.book_id = key
        model.book_title = String(self.bookTitle)
        model.book_author = String(self.authorTitle)
        model.imageType = "1"
        model.imageStr = imageStr
        model.status = "0"
        LocalData().saveHomeBookInfoModel(infoModel: model)
        if self.backEnve != nil {
            self.backEnve!()
        }
        dismissBtnClick()
        UIWindow().currentWindow()?.makeToast("添加成功！", duration: 2.0, position: CSToastPositionCenter)
    }
}
